home *** CD-ROM | disk | FTP | other *** search
/ Komputer for Alle 2004 #2 / K-CD-2-2004.ISO / OpenOffice Sv / f_0397 / python-core-2.2.2 / lib / ConfigParser.py < prev    next >
Encoding:
Python Source  |  2003-07-18  |  16.8 KB  |  473 lines

  1. """Configuration file parser.
  2.  
  3. A setup file consists of sections, lead by a "[section]" header,
  4. and followed by "name: value" entries, with continuations and such in
  5. the style of RFC 822.
  6.  
  7. The option values can contain format strings which refer to other values in
  8. the same section, or values in a special [DEFAULT] section.
  9.  
  10. For example:
  11.  
  12.     something: %(dir)s/whatever
  13.  
  14. would resolve the "%(dir)s" to the value of dir.  All reference
  15. expansions are done late, on demand.
  16.  
  17. Intrinsic defaults can be specified by passing them into the
  18. ConfigParser constructor as a dictionary.
  19.  
  20. class:
  21.  
  22. ConfigParser -- responsible for for parsing a list of
  23.                 configuration files, and managing the parsed database.
  24.  
  25.     methods:
  26.  
  27.     __init__(defaults=None)
  28.         create the parser and specify a dictionary of intrinsic defaults.  The
  29.         keys must be strings, the values must be appropriate for %()s string
  30.         interpolation.  Note that `__name__' is always an intrinsic default;
  31.         it's value is the section's name.
  32.  
  33.     sections()
  34.         return all the configuration section names, sans DEFAULT
  35.  
  36.     has_section(section)
  37.         return whether the given section exists
  38.  
  39.     has_option(section, option)
  40.         return whether the given option exists in the given section
  41.  
  42.     options(section)
  43.         return list of configuration options for the named section
  44.  
  45.     read(filenames)
  46.         read and parse the list of named configuration files, given by
  47.         name.  A single filename is also allowed.  Non-existing files
  48.         are ignored.
  49.  
  50.     readfp(fp, filename=None)
  51.         read and parse one configuration file, given as a file object.
  52.         The filename defaults to fp.name; it is only used in error
  53.         messages (if fp has no `name' attribute, the string `<???>' is used).
  54.  
  55.     get(section, option, raw=0, vars=None)
  56.         return a string value for the named option.  All % interpolations are
  57.         expanded in the return values, based on the defaults passed into the
  58.         constructor and the DEFAULT section.  Additional substitutions may be
  59.         provided using the `vars' argument, which must be a dictionary whose
  60.         contents override any pre-existing defaults.
  61.  
  62.     getint(section, options)
  63.         like get(), but convert value to an integer
  64.  
  65.     getfloat(section, options)
  66.         like get(), but convert value to a float
  67.  
  68.     getboolean(section, options)
  69.         like get(), but convert value to a boolean (currently case
  70.         insensitively defined as 0, false, no, off for 0, and 1, true,
  71.         yes, on for 1).  Returns 0 or 1.
  72.  
  73.     remove_section(section)
  74.         remove the given file section and all its options
  75.  
  76.     remove_option(section, option)
  77.         remove the given option from the given section
  78.  
  79.     set(section, option, value)
  80.         set the given option
  81.  
  82.     write(fp)
  83.         write the configuration state in .ini format
  84. """
  85.  
  86. import re
  87. import types
  88.  
  89. __all__ = ["NoSectionError","DuplicateSectionError","NoOptionError",
  90.            "InterpolationError","InterpolationDepthError","ParsingError",
  91.            "MissingSectionHeaderError","ConfigParser",
  92.            "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
  93.  
  94. DEFAULTSECT = "DEFAULT"
  95.  
  96. MAX_INTERPOLATION_DEPTH = 10
  97.  
  98.  
  99.  
  100. # exception classes
  101. class Error(Exception):
  102.     def __init__(self, msg=''):
  103.         self._msg = msg
  104.         Exception.__init__(self, msg)
  105.     def __repr__(self):
  106.         return self._msg
  107.     __str__ = __repr__
  108.  
  109. class NoSectionError(Error):
  110.     def __init__(self, section):
  111.         Error.__init__(self, 'No section: %s' % section)
  112.         self.section = section
  113.  
  114. class DuplicateSectionError(Error):
  115.     def __init__(self, section):
  116.         Error.__init__(self, "Section %s already exists" % section)
  117.         self.section = section
  118.  
  119. class NoOptionError(Error):
  120.     def __init__(self, option, section):
  121.         Error.__init__(self, "No option `%s' in section: %s" %
  122.                        (option, section))
  123.         self.option = option
  124.         self.section = section
  125.  
  126. class InterpolationError(Error):
  127.     def __init__(self, reference, option, section, rawval):
  128.         Error.__init__(self,
  129.                        "Bad value substitution:\n"
  130.                        "\tsection: [%s]\n"
  131.                        "\toption : %s\n"
  132.                        "\tkey    : %s\n"
  133.                        "\trawval : %s\n"
  134.                        % (section, option, reference, rawval))
  135.         self.reference = reference
  136.         self.option = option
  137.         self.section = section
  138.  
  139. class InterpolationDepthError(Error):
  140.     def __init__(self, option, section, rawval):
  141.         Error.__init__(self,
  142.                        "Value interpolation too deeply recursive:\n"
  143.                        "\tsection: [%s]\n"
  144.                        "\toption : %s\n"
  145.                        "\trawval : %s\n"
  146.                        % (section, option, rawval))
  147.         self.option = option
  148.         self.section = section
  149.  
  150. class ParsingError(Error):
  151.     def __init__(self, filename):
  152.         Error.__init__(self, 'File contains parsing errors: %s' % filename)
  153.         self.filename = filename
  154.         self.errors = []
  155.  
  156.     def append(self, lineno, line):
  157.         self.errors.append((lineno, line))
  158.         self._msg = self._msg + '\n\t[line %2d]: %s' % (lineno, line)
  159.  
  160. class MissingSectionHeaderError(ParsingError):
  161.     def __init__(self, filename, lineno, line):
  162.         Error.__init__(
  163.             self,
  164.             'File contains no section headers.\nfile: %s, line: %d\n%s' %
  165.             (filename, lineno, line))
  166.         self.filename = filename
  167.         self.lineno = lineno
  168.         self.line = line
  169.  
  170.  
  171.  
  172. class ConfigParser:
  173.     def __init__(self, defaults=None):
  174.         self.__sections = {}
  175.         if defaults is None:
  176.             self.__defaults = {}
  177.         else:
  178.             self.__defaults = defaults
  179.  
  180.     def defaults(self):
  181.         return self.__defaults
  182.  
  183.     def sections(self):
  184.         """Return a list of section names, excluding [DEFAULT]"""
  185.         # self.__sections will never have [DEFAULT] in it
  186.         return self.__sections.keys()
  187.  
  188.     def add_section(self, section):
  189.         """Create a new section in the configuration.
  190.  
  191.         Raise DuplicateSectionError if a section by the specified name
  192.         already exists.
  193.         """
  194.         if section in self.__sections:
  195.             raise DuplicateSectionError(section)
  196.         self.__sections[section] = {}
  197.  
  198.     def has_section(self, section):
  199.         """Indicate whether the named section is present in the configuration.
  200.  
  201.         The DEFAULT section is not acknowledged.
  202.         """
  203.         return section in self.__sections
  204.  
  205.     def options(self, section):
  206.         """Return a list of option names for the given section name."""
  207.         try:
  208.             opts = self.__sections[section].copy()
  209.         except KeyError:
  210.             raise NoSectionError(section)
  211.         opts.update(self.__defaults)
  212.         if '__name__' in opts:
  213.             del opts['__name__']
  214.         return opts.keys()
  215.  
  216.     def read(self, filenames):
  217.         """Read and parse a filename or a list of filenames.
  218.  
  219.         Files that cannot be opened are silently ignored; this is
  220.         designed so that you can specify a list of potential
  221.         configuration file locations (e.g. current directory, user's
  222.         home directory, systemwide directory), and all existing
  223.         configuration files in the list will be read.  A single
  224.         filename may also be given.
  225.         """
  226.         if isinstance(filenames, types.StringTypes):
  227.             filenames = [filenames]
  228.         for filename in filenames:
  229.             try:
  230.                 fp = open(filename)
  231.             except IOError:
  232.                 continue
  233.             self.__read(fp, filename)
  234.             fp.close()
  235.  
  236.     def readfp(self, fp, filename=None):
  237.         """Like read() but the argument must be a file-like object.
  238.  
  239.         The `fp' argument must have a `readline' method.  Optional
  240.         second argument is the `filename', which if not given, is
  241.         taken from fp.name.  If fp has no `name' attribute, `<???>' is
  242.         used.
  243.  
  244.         """
  245.         if filename is None:
  246.             try:
  247.                 filename = fp.name
  248.             except AttributeError:
  249.                 filename = '<???>'
  250.         self.__read(fp, filename)
  251.  
  252.     def get(self, section, option, raw=0, vars=None):
  253.         """Get an option value for a given section.
  254.  
  255.         All % interpolations are expanded in the return values, based on the
  256.         defaults passed into the constructor, unless the optional argument
  257.         `raw' is true.  Additional substitutions may be provided using the
  258.         `vars' argument, which must be a dictionary whose contents overrides
  259.         any pre-existing defaults.
  260.  
  261.         The section DEFAULT is special.
  262.         """
  263.         d = self.__defaults.copy()
  264.         try:
  265.             d.update(self.__sections[section])
  266.         except KeyError:
  267.             if section != DEFAULTSECT:
  268.                 raise NoSectionError(section)
  269.         # Update with the entry specific variables
  270.         if vars is not None:
  271.             d.update(vars)
  272.         option = self.optionxform(option)
  273.         try:
  274.             value = d[option]
  275.         except KeyError:
  276.             raise NoOptionError(option, section)
  277.  
  278.         if raw:
  279.             return value
  280.         return self._interpolate(section, option, value, d)
  281.  
  282.     def _interpolate(self, section, option, rawval, vars):
  283.         # do the string interpolation
  284.         value = rawval
  285.         depth = MAX_INTERPOLATION_DEPTH
  286.         while depth:                    # Loop through this until it's done
  287.             depth -= 1
  288.             if value.find("%(") != -1:
  289.                 try:
  290.                     value = value % vars
  291.                 except KeyError, key:
  292.                     raise InterpolationError(key, option, section, rawval)
  293.             else:
  294.                 break
  295.         if value.find("%(") != -1:
  296.             raise InterpolationDepthError(option, section, rawval)
  297.         return value
  298.  
  299.     def __get(self, section, conv, option):
  300.         return conv(self.get(section, option))
  301.  
  302.     def getint(self, section, option):
  303.         return self.__get(section, int, option)
  304.  
  305.     def getfloat(self, section, option):
  306.         return self.__get(section, float, option)
  307.  
  308.     _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
  309.                        '0': False, 'no': False, 'false': False, 'off': False}
  310.  
  311.     def getboolean(self, section, option):
  312.         v = self.get(section, option)
  313.         if v.lower() not in self._boolean_states:
  314.             raise ValueError, 'Not a boolean: %s' % v
  315.         return self._boolean_states[v.lower()]
  316.  
  317.     def optionxform(self, optionstr):
  318.         return optionstr.lower()
  319.  
  320.     def has_option(self, section, option):
  321.         """Check for the existence of a given option in a given section."""
  322.         if not section or section == DEFAULTSECT:
  323.             option = self.optionxform(option)
  324.             return option in self.__defaults
  325.         elif section not in self.__sections:
  326.             return 0
  327.         else:
  328.             option = self.optionxform(option)
  329.             return (option in self.__sections[section]
  330.                     or option in self.__defaults)
  331.  
  332.     def set(self, section, option, value):
  333.         """Set an option."""
  334.         if not section or section == DEFAULTSECT:
  335.             sectdict = self.__defaults
  336.         else:
  337.             try:
  338.                 sectdict = self.__sections[section]
  339.             except KeyError:
  340.                 raise NoSectionError(section)
  341.         sectdict[self.optionxform(option)] = value
  342.  
  343.     def write(self, fp):
  344.         """Write an .ini-format representation of the configuration state."""
  345.         if self.__defaults:
  346.             fp.write("[%s]\n" % DEFAULTSECT)
  347.             for (key, value) in self.__defaults.items():
  348.                 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
  349.             fp.write("\n")
  350.         for section in self.__sections:
  351.             fp.write("[%s]\n" % section)
  352.             for (key, value) in self.__sections[section].items():
  353.                 if key != "__name__":
  354.                     fp.write("%s = %s\n" %
  355.                              (key, str(value).replace('\n', '\n\t')))
  356.             fp.write("\n")
  357.  
  358.     def remove_option(self, section, option):
  359.         """Remove an option."""
  360.         if not section or section == DEFAULTSECT:
  361.             sectdict = self.__defaults
  362.         else:
  363.             try:
  364.                 sectdict = self.__sections[section]
  365.             except KeyError:
  366.                 raise NoSectionError(section)
  367.         option = self.optionxform(option)
  368.         existed = option in sectdict
  369.         if existed:
  370.             del sectdict[option]
  371.         return existed
  372.  
  373.     def remove_section(self, section):
  374.         """Remove a file section."""
  375.         existed = section in self.__sections
  376.         if existed:
  377.             del self.__sections[section]
  378.         return existed
  379.  
  380.     #
  381.     # Regular expressions for parsing section headers and options.
  382.     #
  383.     SECTCRE = re.compile(
  384.         r'\['                                 # [
  385.         r'(?P<header>[^]]+)'                  # very permissive!
  386.         r'\]'                                 # ]
  387.         )
  388.     OPTCRE = re.compile(
  389.         r'(?P<option>[^:=\s][^:=]*)'          # very permissive!
  390.         r'\s*(?P<vi>[:=])\s*'                 # any number of space/tab,
  391.                                               # followed by separator
  392.                                               # (either : or =), followed
  393.                                               # by any # space/tab
  394.         r'(?P<value>.*)$'                     # everything up to eol
  395.         )
  396.  
  397.     def __read(self, fp, fpname):
  398.         """Parse a sectioned setup file.
  399.  
  400.         The sections in setup file contains a title line at the top,
  401.         indicated by a name in square brackets (`[]'), plus key/value
  402.         options lines, indicated by `name: value' format lines.
  403.         Continuation are represented by an embedded newline then
  404.         leading whitespace.  Blank lines, lines beginning with a '#',
  405.         and just about everything else is ignored.
  406.         """
  407.         cursect = None                            # None, or a dictionary
  408.         optname = None
  409.         lineno = 0
  410.         e = None                                  # None, or an exception
  411.         while 1:
  412.             line = fp.readline()
  413.             if not line:
  414.                 break
  415.             lineno = lineno + 1
  416.             # comment or blank line?
  417.             if line.strip() == '' or line[0] in '#;':
  418.                 continue
  419.             if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
  420.                 # no leading whitespace
  421.                 continue
  422.             # continuation line?
  423.             if line[0].isspace() and cursect is not None and optname:
  424.                 value = line.strip()
  425.                 if value:
  426.                     cursect[optname] = "%s\n%s" % (cursect[optname], value)
  427.             # a section header or option header?
  428.             else:
  429.                 # is it a section header?
  430.                 mo = self.SECTCRE.match(line)
  431.                 if mo:
  432.                     sectname = mo.group('header')
  433.                     if sectname in self.__sections:
  434.                         cursect = self.__sections[sectname]
  435.                     elif sectname == DEFAULTSECT:
  436.                         cursect = self.__defaults
  437.                     else:
  438.                         cursect = {'__name__': sectname}
  439.                         self.__sections[sectname] = cursect
  440.                     # So sections can't start with a continuation line
  441.                     optname = None
  442.                 # no section header in the file?
  443.                 elif cursect is None:
  444.                     raise MissingSectionHeaderError(fpname, lineno, `line`)
  445.                 # an option line?
  446.                 else:
  447.                     mo = self.OPTCRE.match(line)
  448.                     if mo:
  449.                         optname, vi, optval = mo.group('option', 'vi', 'value')
  450.                         if vi in ('=', ':') and ';' in optval:
  451.                             # ';' is a comment delimiter only if it follows
  452.                             # a spacing character
  453.                             pos = optval.find(';')
  454.                             if pos != -1 and optval[pos-1].isspace():
  455.                                 optval = optval[:pos]
  456.                         optval = optval.strip()
  457.                         # allow empty values
  458.                         if optval == '""':
  459.                             optval = ''
  460.                         optname = self.optionxform(optname.rstrip())
  461.                         cursect[optname] = optval
  462.                     else:
  463.                         # a non-fatal parsing error occurred.  set up the
  464.                         # exception but keep going. the exception will be
  465.                         # raised at the end of the file and will contain a
  466.                         # list of all bogus lines
  467.                         if not e:
  468.                             e = ParsingError(fpname)
  469.                         e.append(lineno, `line`)
  470.         # if any parsing errors occurred, raise an exception
  471.         if e:
  472.             raise e
  473.